/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stuff.web;

import java.util.LinkedList;
import java.util.List;

import javax.validation.Valid;
import javax.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stuff.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import stuff.util.MailManager;
import stuff.util.PasswordPseudoGenerator;
import org.springframework.web.bind.annotation.SessionAttributes;
import stuff.ext.AccountDetsImpl;

/**
 *
 * @author Николай
 */
@Controller
@SessionAttributes("account")
public class AccountCntrl {

    final private Logger log = LoggerFactory.getLogger(AccountCntrl.class);
    private DictionaryManager dicMng;
    private MailManager mailMng;
    private AccountManager accMng;
    private Validator validator;
    private Country nullCountry = new Country("<NOT SPECEFIED>");

    @Autowired
    public AccountCntrl(
            DictionaryManager dicMng,
            AccountManager accMng,
            MailManager mailMng,
            Validator val
            ) {
        this.dicMng = dicMng;
        this.accMng = accMng;
        this.mailMng = mailMng;
        this.validator = val;
    }

    @ModelAttribute("account")
    public Account getAccount() {
        return new Account();
    }

    @ModelAttribute("countries")
    public List<Country> getCountries() {
        List<Country> cl = new LinkedList<Country>();
        cl.add(nullCountry);
        cl.addAll(dicMng.getCountries());
        return cl;
    }

    @RequestMapping(value = "/account/create/", method = RequestMethod.GET)
    public String setForm(
            @ModelAttribute("account") @Valid Account acc,
            BindingResult result) {
        new RegistrationValidator().validate(acc, accMng, result);
        return "createAccount";
    }

    @RequestMapping(value = "/account/create/{field}", method = RequestMethod.POST)
    public
    @ResponseBody JSONResponse submitdField(
                @PathVariable String field,
                @ModelAttribute("account") Account acc,
                BindingResult result) {

        log.debug(acc.toString());
        log.debug(result.toString());
        JSONResponse response = new JSONResponse(validator.validateProperty(acc, field));
        log.debug("response state " + response.getState());
        log.debug(response.getMsg().toString());
        return response;
    }

    @RequestMapping(value = "/account/create/", method = RequestMethod.POST)
    public String submitAccount(
            Model model,
            @ModelAttribute("account") @Valid Account acc,
            BindingResult result,
            SessionStatus status) {

        new RegistrationValidator().validate(acc, accMng, result);
        log.debug("show account " + model.asMap().toString());
        if (result.hasErrors()) {
            return "redirect:/account/create/";
        } else {
            String pwd = new PasswordPseudoGenerator().getPassword(8);
            acc.setPassword(pwd);
            mailMng.sendPassword(acc);
            accMng.addAccount(acc);
            status.setComplete();
            return "redirect:/account/successfully";
        }
    }

    @RequestMapping(value="/account/", method=RequestMethod.GET)
    public String setEditForm(Model model) {

        Account acc;
        Object obj = SecurityContextHolder.
                getContext().
                getAuthentication().
                getPrincipal();
        if (obj instanceof AccountDetsImpl) {
            acc = ((AccountDetsImpl)obj).getAccount();
        } else {
            acc = new Account();
        }
        model.addAttribute("account", acc);
        return "createAccount";
    }

    @RequestMapping(value="/account/{id}", method=RequestMethod.GET)
    public String setEditForm(Model model, @PathVariable long id) {
        Account acc = accMng.getAccount(id);
        model.addAttribute("account", acc);
        return "createAccount";
    }


}
